#include <stdio.h>
#include <omp.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include "user_buzz.h"
#include <sys/types.h>
#include <sys/syscall.h>


#define THREADCOUNT 100
#define GOLD 30
#define BLACK THREADCOUNT-GOLD
#define THREADPOOL 5   

#define TIMEOUT 10  // in us
#define ACTIVITY 5 // in us
bzz_t GTLOCK;

void thread(){
    struct timeval t1,t2,t3,t4;
    double elapsedTime, releaseelapsedTime;
    int ID = omp_get_thread_num();
    
    if(ID<=GOLD) bzz_color(BZZ_GOLD,GTLOCK); 
    else  bzz_color(BZZ_BLACK,GTLOCK);     // SET COLOR OF LOCK HERE Depending on condiion
    
    gettimeofday(&t1,NULL);
    bzz_lock(GTLOCK);
    gettimeofday(&t2,NULL);
    usleep(ACTIVITY); // ACTIVITY
    gettimeofday(&t3,NULL);
    bzz_release(GTLOCK);
    gettimeofday(&t4,NULL);
    
    elapsedTime = (t2.tv_sec - t1.tv_sec);      // sec 
    elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000000.0;   //  us
    
    releaseelapsedTime = (t4.tv_sec - t3.tv_sec);      // sec 
    releaseelapsedTime += (t4.tv_usec - t3.tv_usec) / 1000000.0;   //  us
    
    
    if(ID<=GOLD) printf("GOLD = %f\n",elapsedTime);
    else printf("BLACK = %f\n",elapsedTime);
    
	
}


int main(){
    
    omp_set_num_threads(THREADCOUNT);
    init_bzz(GTLOCK,THREADPOOL,TIMEOUT); 
    
    
#pragma omp parallel num_threads(100)
    {
        
        thread();
        
    }
    
    bzz_kill(GTLOCK);
    
}


